# @Version        : 1.0
# @Update Time    : 2024/12/11 22:19
# @File           : role_view.py
# @IDE            : PyCharm
# @Desc           : 文件描述信息

from fastapi import APIRouter, Depends
from fastapi_utils.cbv import cbv
from sqlalchemy import and_

from authx.dependencies.permission import PermissionChecker
from src import schemas, models
from src.core.base_controller import BaseController
from src.core.dependencies import IdList
from src.core.response.response_schema import (
    ResponseGenericSchema,
    ResponseSchema,
    PageResponse,
)
from src.db.db_database import alchemy
from src.models import SysRole
from src.schemas.role_schema import RoleParams
from src.services.role_service import RoleService

router = APIRouter()


@cbv(router)
class RoleController(BaseController):

    role_service: RoleService = Depends(alchemy.provide_service(RoleService))

    @router.get(
        "/list",
        summary="角色列表",
        response_model=PageResponse[schemas.RoleOut],
        dependencies=[Depends(PermissionChecker("system:role:list"))],
    )
    async def get_role_list(self, param: RoleParams = Depends()):
        where = await param.get_where_and_limit_offset(SysRole)
        res, count = await self.role_service.list_and_count(*where)
        return self.paginated_response(
            data=res, total=count, current=param.page, size=param.limit
        )

    # 获取所有角色数据
    @router.get(
        "/getAllRoles",
        summary="获取所有角色数据",
        response_model=ResponseGenericSchema[list[schemas.RoleOut]],
        dependencies=[Depends(PermissionChecker("system:role:list"))],
    )
    async def get_all_roles(self):
        res = await self.role_service.list()
        return self.success(data=res)

    @router.post(
        "/add",
        summary="创建角色",
        description="创建角色",
        dependencies=[Depends(PermissionChecker("system:role:add"))],
        response_model=ResponseSchema,
    )
    async def add_role(
        self,
        model: schemas.RoleCreate,
    ):
        model.role_sort = 0
        await self.role_service.create(model, auto_commit=True)
        return self.success(message="创建成功")

    @router.put(
        "/update",
        summary="更新角色",
        description="更新角色",
        dependencies=[Depends(PermissionChecker("system:role:update"))],
        response_model=ResponseSchema,
    )
    async def update_role(
        self,
        model: schemas.RoleUpdate,
    ):
        await self.role_service.update(model, auto_commit=True)
        return self.success(message="更新成功")

    @router.delete(
        "/delete",
        summary="删除角色",
        description="删除角色",
        dependencies=[Depends(PermissionChecker("system:role:delete"))],
        response_model=ResponseSchema,
    )
    async def delete_role(
        self,
        ids: IdList = Depends(),
    ):
        await self.role_service.delete_many(ids.ids, auto_commit=True)
        return self.success(message="删除成功")

    # 根据角色id查询角色菜单id
    @router.get(
        "/getRoleMenuIds",
        summary="根据角色id查询角色菜单id",
        dependencies=[Depends(PermissionChecker("system:role:list"))],
        response_model=ResponseGenericSchema[dict],
    )
    async def get_role_menu_ids(self, role_id: int):
        res = await self.role_service.get_one_or_none(
            and_(models.SysRole.id == role_id),
            load=[models.SysRole.menus, models.SysRole.depts],
        )
        if not res:
            return self.error(message="角色不存在")
        menu_ids = [item.id for item in res.menus]
        dept_ids = [item.id for item in res.depts]
        return self.success(
            data={
                "menuIds": menu_ids,
                "homeKey": res.home_key,
                "dataScope": res.data_scope,
                "deptIds": dept_ids,
            }
        )

    # 修改角色菜单权限
    @router.put(
        "/update/permissions",
        summary="修改角色菜单权限",
        description="修改角色菜单权限",
        dependencies=[Depends(PermissionChecker("system:role:distribute"))],
        response_model=ResponseSchema,
    )
    async def update_role_permissions(
        self,
        model: schemas.RolePermissionsSchema,
    ):
        await self.role_service.update_role_permissions(model)
        return self.success(message="修改成功")
